package api

import (
	"fmt"
	"github.com/LyricTian/captcha"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"go-admin-server/app/dto/response"
	"go-admin-server/app/service"
	"go-admin-server/common/errors"
	"go-admin-server/common/utils"
)

type publicApi struct{}

var store = base64Captcha.DefaultMemStore

func NewPublicHttp(group *gin.RouterGroup) {
	s := &publicApi{}
	group.GET("/pub/captchaId", s.GetCaptchaId)
	group.GET("/pub/captchaImage", s.GetCaptchaImage)
	group.GET("/pub/captcha", s.Captcha)
}

func (a *publicApi) Captcha(c *gin.Context) {
	utils.GetClientIP(c)

	// 生成默认数字
	driver := base64Captcha.DefaultDriverDigit
	// 生成base64图片
	cap := base64Captcha.NewCaptcha(driver, store)
	// 获取
	id, b64s, err := cap.Generate()
	if err != nil {
		fmt.Println("Register GetCaptchaPhoto get base64Captcha has err:", err)
		response.Error(c, err)
	}
	mp := make(map[string]string)
	mp["id"] = id
	mp["b64s"] = b64s
	response.Success(c, mp)
}

// 验证验证码
func Verify2(id string, val string) bool {
	if id == "" || val == "" {
		return false
	}
	// 同时在内存清理掉这个图片
	return store.Verify(id, val, true)
}

func (a *publicApi) GetCaptchaId(c *gin.Context) {
	ctx := c.Request.Context()
	item, err := service.LoginService.GetCaptchaId(ctx, 4)
	if err != nil {
		response.Error(c, err)
		return
	}
	response.Success(c, item)
}

func (a *publicApi) GetCaptchaImage(c *gin.Context) {
	utils.GetClientIP(c)
	captchaID := c.Query("id")
	Width := c.Query("width")
	Height := c.Query("height")
	if captchaID == "" {
		response.Error(c, errors.New400Response("captcha id not empty"))
		return
	}
	if c.Query("reload") != "" {
		if !captcha.Reload(captchaID) {
			response.Error(c, errors.New400Response("not found captcha id"))
			return
		}
	}
	err := service.LoginService.GetCaptchaImage(c, c.Writer, captchaID, utils.String2Int(Width), utils.String2Int(Height))
	if err != nil {
		response.Error(c, err)
	}
}
